package com.tommy.store.http;

import java.io.ByteArrayInputStream;
import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.util.EntityUtils;

public class MyHttpPut {
    public static void main(String[] args) {

    }

    public static String request(String url, String fileName, String content) {

        // String urlBase = "https://openapi.alipan.com";

        String result = "";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut(url); // 目标URL

            // 准备上传的文件
            // File file = new File("/path/to/your/file.txt");
            byte[] byteArray = content.getBytes("UTF-8");

            // 设置请求体（MultipartForm-Data）
            BasicHttpEntity entity = new BasicHttpEntity();
            entity.setContent(new ByteArrayInputStream(byteArray));
            // entity.setContentLength(content.getBytes().length);

            // 设置PUT请求的实体
            httpPut.setEntity(entity);

            // 执行请求
            HttpResponse response = httpClient.execute(httpPut);

            // 打印响应状态
            System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

            // 打印响应内容
            result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
